package com.googlecode.nauka.dbfactory;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBFactory{
    private static DBFactory db;
    private Connection       connection;
    private String           dburl;
    private String           username;
    private String           password;

    public static DBFactory getDb(){
        return db;
    }

    public static void setDb(DBFactory db){
        DBFactory.db = db;
    }

    public DBFactory(String jarLocation, String classname, String dburl)
        throws Exception{

        this.dburl = dburl;
        registerDriver(jarLocation, classname);
    }

    public Connection getConnection() throws SQLException{
        if(connection != null)
            return connection;
        if(username != null)
            connection = DriverManager.getConnection(dburl, username, password);
        else
            connection = DriverManager.getConnection(dburl);
        return connection;
    }

    private void registerDriver(String file, String classname) throws Exception{
        URL u = new File(file).toURL();
        URLClassLoader ucl = new URLClassLoader(new URL[]{u});
        Driver d = (Driver)Class.forName(classname, true, ucl).newInstance();
        Driver driver = new DriverShim(d);
        DriverManager.registerDriver(driver);
    }

    public PreparedStatement prepareStatement(String sql) throws SQLException{
        return getConnection().prepareStatement(sql);
    }

    public void close() throws SQLException{
        getConnection().close();
        connection = null;
    }

    public void setUsername(String username){
        this.username = username;
    }

    public void setPassword(String password){
        this.password = password;
    }

}
